package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 用户服务
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private MenuDao menuDao;
    //根据用户名查询数据库获取用户信息和关联的角色信息，同时需要查询角色关联的权限信息
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);//查询用户基本信息，不包含用户的角色
        if(user == null){
            return null;
        }
        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色ID查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);//让角色关联权限
        }
        user.setRoles(roles);//让用户关联角色
        return user;
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);

        Page<User> userPage = userDao.findByCondition(queryString);
        long total = userPage.getTotal();
        List<User> result = userPage.getResult();
        for (User user : result) {
            if (user.getPassword()!=null){
                user.setPassword("************");
            }
        }
        PageResult pageResult = new PageResult(total, result);
        return pageResult;
    }

    //新增用户同时关联角色表
    @Override
    public void add(User user, Integer[] roleIds) {
        //数据加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(password);
        //新增用户，操作t_user表
        userDao.add(user);
        //设置角色和用户的关联关系，操作中间表
        Integer id = user.getId();
        this.setUserAndRole(id,roleIds);
    }

    public void setUserAndRole(Integer userId, Integer[] roleIds) {
        if (roleIds!=null && roleIds.length>0){
            for (Integer roleId : roleIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("userId",userId);
                map.put("roleId",roleId);
                userDao.setUserAndRole(map);
            }
        }
    }

    //编辑用户信息，同时需要关联角色
    public void edit(User user, Integer[] roleIds) {
        //修改用户基本信息，操作用户t_user表
        userDao.edit(user);
        //清理当前用户关联的角色，操作中间关系表t_user_role表
        userDao.deleteByUserId(user.getId());
        //重新建立当前用户和角色的关联关系
        Integer id = user.getId();
        this.setUserAndRole(id,roleIds);
    }

    public void delete(Integer id){
        //判断是否关联角色
        long count = userDao.findCountByUserId(id);
        if (count>0){
            //当前用户已经关联,不能删除
            throw new RuntimeException("当前权限被引用,不能删除");
        }
        userDao.delete(id);
    }

    @Override
    public User findById(Integer id) {
        User user = userDao.findById(id);
        if (user!=null){
            user.setPassword("************");
        }
        return user;
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }

    @Override
    public List<Map<String, Object>> getMenu(Integer id) {

        List<Map<String, Object>>list=null;

        Set<Role> role = menuDao.findByUsername(id);

        //根据角色id查询该角色拥有的权限
        // Set<Permission> permission = permissionDao.findByRoleId(role.getId());
        for (Role role1 : role) {
            list= menuDao.findByRoleIdPerson(role1.getId());
            for (Map<String, Object> map : list) {
                Integer id1 = (Integer) map.get("id");//父类id
                //使用父类id查询子类id
                List<Map<String, Object>> children = menuDao.findByPersonId(id1);
                map.put("children",children);
            }
        }
        return list;
    }
}
